<template>
<!--  服务器状态-->
<!--  <div :class="{ 'bg-success': serverState, 'bg-danger': !serverState }" class="card text-center ms-2 me-4 mt-2 mb-2">-->
  <div :class="{ 'bg-primary-light': serverState, 'bg-danger-light': !serverState }" class="card text-center ms-2 me-4 mt-2 mb-2">
    <div class="card-body">
      <h5 class="text-white">{{ serverState ? '聚合服务器诚实' : '聚合服务器恶意' }}</h5>
    </div>
  </div>
<!-- 客户端状态 -->
  <div class="card text-center  ms-2 me-4 mt-2 mb-2">
    <div class="card-body">
      <h5 class="">客户端</h5>
        <div class="table-responsive">
          <table class="table">
            <thead>
              <tr>
                <th scope="col">用户</th>
                <th v-for="(user, index) in Homeclients" :key="'user_' + index" scope="col">{{ user.name }}</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>状态</td>
                <td class="text-white" v-for="(user, index) in Homeclients" :key="'user_status_' + index" :class="{ 'bg-primary-light': user.status1, 'bg-danger-light': !user.status1 }">{{ user.status2 }}</td>
              </tr>
            </tbody>
          </table>
        </div>
    </div>
  </div>
<!-- 追踪服务器状态 -->
  <div class="card text-center  ms-2 me-4 mt-2 mb-2">
    <div class="card-body ">
      <h5 class="">追踪服务器</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in Homeserver" :key="'user_' + index" scope="col">{{ user.name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr >
              <td>状态</td>
              <td class="text-white" v-for="(user, index) in Homeserver" :key="'user_status_' + index" :class="{ 'bg-primary-light': user.status, 'bg-danger-light': !user.status }">{{(user.status ? '诚实' : '恶意') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="d-flex align-items-center">
    <button type="button" class="btn btn-primary btn-lg text-center ms-2 me-4 mt-2 mb-2" @click="initializeBackend">初始化</button>
     <p class="mb-0">{{ responseInitial }} </p>
  </div>

</template>

<script setup>
import {ref, onMounted, onUnmounted, computed} from 'vue';
import {AggserverInitialEventBus, ClientInitialEventBus, HomeeventBus} from '@/views/event-bus';
// 引入 Axios
import axios from 'axios';


const responseInitial=ref("")
// 初始加载的固定数据
const initialClients = [
  { name: 'user1', status1: true, status2:"默认设置"},
  { name: 'user2', status1: true, status2: "默认设置" },
  { name: 'user3', status1: true, status2: "默认设置"},
  { name: 'user4', status1: true, status2:"默认设置" },
  { name: 'user5', status1: true, status2: "默认设置"},
  { name: 'user6', status1: true, status2: "默认设置" },
  { name: 'user7', status1: true, status2: "默认设置" },
  { name: 'user8', status1: true, status2: "默认设置" },
  { name: 'user9', status1: true, status2:"默认设置" },
  { name: 'user10', status1: true, status2:"默认设置" },
];
const initialserver = [
  { name: '服务器', status: true },
  { name: 'user1', status: true },
  { name: 'user2', status: true },
  { name: 'user3', status: true },
  { name: 'user4', status: true },
  { name: 'user5', status: false },
  { name: 'user6', status: false },
  { name: 'user7', status: false },
  { name: 'user8', status: false },
  { name: 'user9', status: true },
  { name: 'user10', status: true },
  // 添加更多用户...
]
const Homeclients = ref([...initialClients]);

const Homeserver = ref([...initialserver]);
const Aggstate = ref([]);
// const serverState = ref(true); // 初始化布尔值，可以根据实际情况修改

const loadHomeFromLocalStorage = (option) => {
  if (option===1){
    const storedHomeclients = JSON.parse(localStorage.getItem('Homeclients'));
    console.log('storedHomeclients:',storedHomeclients);
    if (storedHomeclients) {
      Homeclients.value = storedHomeclients;
    } else {
     Homeclients.value = [...initialClients];
    }
  }
  if(option===2){
    const storedHomeserver = JSON.parse(localStorage.getItem('TraceResult'));
    console.log('storedHomeserver:',storedHomeserver);
    if (storedHomeserver) {
      Homeserver.value = storedHomeserver;
    } else {
     Homeserver.value = [...initialserver];
    }
  }
  if(option===3){
    const storedAggstates = JSON.parse(localStorage.getItem('Aggstates'));
    console.log("store_Aggstate:",storedAggstates)
    Aggstate.value = storedAggstates;
  }
};

// 将用户设置保存到本地存储
const saveHomeToLocalStorage = (option) => {
  if (option===1){
    // const rawHomeclients = Homeclients.value.map(homeclient => ({ ...homeclient}));
    localStorage.setItem('Homeclients', JSON.stringify(Homeclients.value));
  }
  // if(option===2){
  //   localStorage.setItem('TraceResult', JSON.stringify(Homeserver.value));
  // }
  // if(option===3){
  //   // const rawAggstates = Aggstates.value.map(state => ({ ...state }));
  //   // localStorage.setItem('Aggstates', JSON.stringify(rawAggstates));
  //   localStorage.setItem('Aggstates', JSON.stringify(Aggstate.value));
  // }
};
// 组件挂载时加载用户设置
onMounted(() => {

  loadHomeFromLocalStorage(1);
  loadHomeFromLocalStorage(2);
  loadHomeFromLocalStorage(3);
  console.log('Component is mounted');
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  saveHomeToLocalStorage(1);
  // saveHomeToLocalStorage(3);
  // saveHomeToLocalStorage(2);
});


const serverState = computed(() => {
  if(!Aggstate.value[1]){
          return true;
  }else{
          return false;
  }
});

// 监听来自初始化按钮的事件，执行初始化操作
ClientInitialEventBus.value.addEventListener('initializePages', () => {
  Homeclients.value = [...initialClients];
    // 将初始数据保存并加载
  saveHomeToLocalStorage(1);
  loadHomeFromLocalStorage(2);
  loadHomeFromLocalStorage(3);
});

// 监听来自文件二的更新事件，并更新 clients 的状态
HomeeventBus.value.addEventListener('updateClients', (event) => {
  const updatedSettings = event.detail;
  console.log("updatedSettings", updatedSettings);

  // 如果收到的更新数据比原始数据长，则进行部分更新
  if (updatedSettings.length > Homeclients.value.length) {
    // 将更新的部分添加到原始数据末尾
    const newUsers = updatedSettings.slice(Homeclients.value.length);
    Homeclients.value.push(...newUsers);
  } else {
    // 否则，进行部分更新
    updatedSettings.forEach((setting, index) => {
      Homeclients.value[index].status2 = setting;
      // 判断 status1 的值
      Homeclients.value[index].status1 = setting === '默认设置';
    });
  }
  // 将更新后的状态保存到本地存储
  // localStorage.setItem('clients', JSON.stringify(Homeclients.value));
  saveHomeToLocalStorage(1);
});

//设置axios
const apiBaseUrl = (window.webConfig && window.webConfig.webApiBaseUrl) || process.env.VUE_APP_BACKEND_API;
const apiClient = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 点击按钮时发送 POST 请求到 Flask 服务器的 /initialize 路由
const initializeBackend = () => {
   responseInitial.value="初始化中..."
  // 触发自定义事件，通知其他页面进行初始化操作
  AggserverInitialEventBus.value.dispatchEvent(new CustomEvent('initializeClients'));
  // 重置 clients 为初始数据
  Homeclients.value = [...initialClients];
  // Homeclients.value = JSON.parse(localStorage.getItem('Clients_users'));
  // Homeserver.value = [...initialserver];
  // 将初始数据保存到本地存储
  saveHomeToLocalStorage(1);
  loadHomeFromLocalStorage(2);
  loadHomeFromLocalStorage(3);

  // saveHomeToLocalStorage(2);
  // 请求
  // axios.post(`${process.env.VUE_APP_BACKEND_API}/run`,{
    apiClient.post(`/run`,{
  // 你的请求数据
}, {
  headers: {
    'Content-Type': 'application/json'
  }
}) // 发送 POST 请求到 Flask 后端的 /initialize 路由
    .then(response => {
      if (response.status === 200) {
        responseInitial.value="初始化完成!"
        console.log(response.data); // 处理后端返回的数据
      }

    })
    .catch(error => {
      console.error(error);
    });
};
// 在此之后，你可以根据需要修改 serverState 的值，以更新背景颜色和文本
</script>
<style scoped>
.bg-primary-light {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
</style>